angular.module('theApp.controllers', [])

.controller('errorController', function($scope, $rootScope, $routeParams) {
    var id = $routeParams.id;
    if (id === undefined) {
        $scope.msg = $rootScope.errors[id];
        return;
    }
    $scope.msg = "Unknown error";
 })
    
.controller('authController', function(root, $rootScope, $location, $route, A) {
    root.onAuth(function(authData) {
        if (authData) {
            console.log("User ID: " + authData.uid + ", Provider: " + authData.provider);
            A.get_user_data_from_provider(root, $rootScope,  $location, $route, authData);
        } else {
            $rootScope.luser = null;
            console.log('No user');
        }
    });
 })
    
.controller('loginController', function(root, $scope) {
        
    $scope.signInSimple = function() {
        root.authWithPassword({
            email: $scope.email,
            password: $scope.password,
            rembember: 'never'
        }, 
        function(error, authData) {
            if (error === null) {
                console.log("User ID: " + authData.uid + ", Provider: " + authData.provider);
            } else {
                switch (error.code) {
                    case "INVALID_USER":
                        var yn = prompt("Do you want to create a new user account for " + $scope.email + "? Type YES if you do", "NO");
                        if (yn === "YES") {
                            alert('OK');                            
                            root.createUser({
                                email: $scope.email,
                                password: $scope.password
                            }, 
                            function(error) {
                                if (error === null) {
                                    console.log("User " + $scope.email + " created successfully");
                                    $scope.signInSimple();
                                } else {
                                    console.log("Error creating user:", error);
                                }
                            });
                        } else {
                            alert('Too bad');                            
                        }
                        break;
                    case "INVALID_PASSWORD":
                        console.log("Error authenticating user:", error);
                        alert('Invalid credentials');
                        break;
                    default:
                        console.log("Error authenticating user:", error);
                        alert('Invalid credentials');
                }
            }
        });
    };

    $scope.signInOAuth = function(provider) {
    
        var scope = "email";
        var options = {};
        options.remember = 'never';
        if (provider === 'facebook') {
            scope = scope + ',public_profile';
        }
        if (provider === 'google') {
            scope = scope + ',profile';
        }
        options.scope = scope;
        root.authWithOAuthRedirect(provider, 
            function(error, authData) { 
                //S.handle
                if (error === null) {
                    console.log("User ID: " + authData.uid + ", Provider: " + authData.provider);
                } else {
                    console.log("Error authenticating user:", error);
                    alert('Invalid credentials');
                }
            },
            options
        );
    };
  
})

.controller('scheduleController', function($scope, root, $rootScope, $firebase, $location, $route, $routeParams, S) {

    $scope.switchApproved = function() {
        $rootScope.approved = !$scope.approved;
        $route.reload();
    };

    if ($rootScope.approved === undefined) {
        $rootScope.approved = true;
    }
    
    $scope.approve = function(x) {
        // mark this request case as approved
        x.ap.approved = true;
        root.child('requests').child(x.r.uid).child('submitted').child(x.ak).set(x.ap);
        // if all sessions are satisfied, hide the remaining cases
        var count = x.r.sessions;
        var aarr = [];
        var original = {};
        Object.keys(x.r.submitted).map(function(k) {
            var e = x.r.submitted[k];
            if (e.approved) {
                count--;
                aarr.push(e);
            }
        });
        if (count === 0) {
            x.r.original = x.r.submitted;
            x.r.submitted = {};
            x.r.approved = aarr;
            root.child('requests').child(x.r.uid).set(x.r);
        }
        $route.reload();
    },

    $('#sswloader').show();

    var fid = $routeParams.fid;
    var tid = $routeParams.tid;
    var tchosen = null;
    var fchosen = null;

    $scope.fieldsallarr.$loaded(function(farr) {
        $('#sswloader').hide();
        
        if (fid !== 'all') {
            fchosen = fid;
        }
        if (tid !== 'all') {
            tchosen = tid;
        }

        // Create the scaffolding with emtpy cells. This is always
        // there. Later we fill the cells as needed.
        var varr = [];
        var d = {};
        farr.forEach(function(field) {
            $scope.field = field;
            varr.push(field);
            d[field.uid] = {};
            d[field.uid].field = field;
            d[field.uid].show = (fchosen === null && tchosen === null || field.uid === fchosen);
            var slots = field.slots;
            slots.forEach(function(slot) {
                d[field.uid][slot] = {};
                $scope.days.forEach(function(day) {
                    d[field.uid][slot][day] = [];
                });
            });
        });
        
        $scope.d = d;

        // scan all requests, and put them in the corresponding cell of the grid.
        root.child('requests').once('value', function(rs) {
        var reqAll = rs.val();        
        angular.forEach(reqAll, function(r) {
            $('#sswloader').show();
            var team = $firebase(root.child('teams').child(Object.keys(r.teams)[0])).$asObject();
            team.$loaded(function() {
    
                $('#sswloader').hide();
                // If there is a chosen team and not this one, skip this team.
                if (team.uid !== tchosen && null !== tchosen) {
                    return;
                }
            
                if (r.submitted instanceof Object) {

                    // put submitted requests in scope
                    var i = 0;
                    Object.keys(r.submitted).map(function(key) { 

                        i++;                        
                        var ap = r.submitted[key];
                        
                        // If there is a chosen field and this request does not use it, skip.
                        if (fchosen !== null && fchosen !== ap.field) {
                            return;
                        }
                        
                        var status = ap.approved ? 'approved' : 'submitted';
                        
                        var box = {"r": r, "ak": key, "t": team, "n": i, "ap": ap, status: status};
                        
                        if (ap.approved || ! $scope.approved) {
                            $scope.d[ap.field][ap.slot][ap.day].push(box);
                            $scope.d[ap.field].show = true;
                        }                        
                    });
                }
                
                if (r.approved instanceof Object) {

                    // put approved requests in scope
                    var i = 0;
                    Object.keys(r.approved).map(function(key) { 

                        i++;                        
                        var ap = r.approved[key];
                        
                        // If there is a chosen field and this request does not use it, skip.
                        if (fchosen !== null && fchosen !== ap.field) {
                            return;
                        }
                        
                        var box = {"r": r, "ak": key, "t": team, "n": i, "ap": ap, status: 'complete'};
                        
                        $scope.d[ap.field][ap.slot][ap.day].push(box);
                        $scope.d[ap.field].show = true;                        
                    });
                }
            });
        });

       });
    });
})

.controller('serverController', function($scope, $http, A) {

    A.send_email($http, $scope, "mlchiodo@gmail.com", "someone@somewhere.com", "a-test-subject", 'this is the text of my message');
    return;
    
    
    var srv = "php/server.php";
    
    //
    //var x = {'op': 'email', 'data': {"a": "111", "b": "222"}};

    $scope.aaa = " Sent ";

    $http.post(srv, {'payload': x})

    .success(function(data, status, headers, config) {

        $scope.aaa += " after-post: " + JSON.stringify(data);

        $http.get('php/read.php').success(function(data, status, headers, config) {

            $scope.aaa += " after-get: " + data;
        })

        .error(function(data, status, headers, config) {
        });

    }).error(function(data, status, headers, config) {
    });


    $scope.aaa += ' Waiting ... ';
 })
 
 
;

